package cn.chiship.framework.business.biz.content.service.impl;

import cn.chiship.framework.business.biz.content.enums.ContentStatusEnum;
import cn.chiship.framework.business.biz.content.pojo.dto.ContentSyncWxPubDto;
import cn.chiship.framework.business.biz.content.pojo.vo.ContentArticleVo;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatArticle;
import cn.chiship.framework.third.biz.wxpub.mapper.ThirdWechatArticleMapper;
import cn.chiship.framework.upms.biz.system.service.UpmsCategoryDictService;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.DateUtils;
import cn.chiship.sdk.core.util.ObjectUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.business.biz.content.mapper.ContentArticleMapper;
import cn.chiship.framework.business.biz.content.entity.ContentArticle;
import cn.chiship.framework.business.biz.content.entity.ContentArticleExample;
import cn.chiship.framework.business.biz.content.service.ContentArticleService;
import cn.chiship.sdk.framework.pojo.vo.PageVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文档详细表业务接口实现层 2024/10/19
 *
 * @author lijian
 */
@Service
public class ContentArticleServiceImpl extends BaseServiceImpl<ContentArticle, ContentArticleExample>
        implements ContentArticleService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContentArticleServiceImpl.class);

    @Resource
    ContentArticleMapper contentArticleMapper;

    @Resource
    UpmsCategoryDictService upmsCategoryDictService;

    @Resource
    ThirdWechatArticleMapper thirdWechatArticleMapper;

    @Override
    public BaseResult page(PageVo pageVo, Map<String, String> paramsMap) {
        Page<Object> pageResult = PageMethod.startPage(pageVo.getCurrent().intValue(), pageVo.getSize().intValue());
        List<ContentArticleVo> articleVos = contentArticleMapper.selectBaseContentDetail(paramsMap);
        List<JSONObject> results = new ArrayList<>();
        for (ContentArticleVo vo : articleVos) {
            JSONObject json = JSON.parseObject(JSON.toJSONString(vo));
            json.putAll(upmsCategoryDictService.getParentInfoById(vo.getCategoryId()));
            results.add(json);
        }
        pageVo.setRecords(results);
        pageVo.setTotal(pageResult.getTotal());
        pageVo.setPages((long) pageResult.getPages());
        return BaseResult.ok(pageVo);
    }

    @Override
    public JSONObject assembleData(ContentArticle contentArticle) {
        JSONObject json = JSON.parseObject(JSON.toJSONString(contentArticle));
        json.putAll(upmsCategoryDictService.getParentInfoById(contentArticle.getCategoryId()));
        return json;
    }

    @Override
    public ContentArticle selectByPrimaryKey(Object id) {
        ContentArticleExample contentArticleExample = new ContentArticleExample();
        contentArticleExample.createCriteria().andIdEqualTo(id.toString());
        List<ContentArticle> contentArticles = contentArticleMapper.selectByExampleWithBLOBs(contentArticleExample);
        if (contentArticles.isEmpty()) {
            return new ContentArticle();
        }
        return contentArticles.get(0);
    }

    @Override
    public BaseResult selectDetailsByPrimaryKey(Object id) {
        ContentArticle contentArticle = selectByPrimaryKey(id);
        if (StringUtil.isNullOrEmpty(contentArticle.getId())) {
            return BaseResult.error("无效的内容资源");
        }

        JSONObject json = JSON.parseObject(JSON.toJSONString(contentArticle));
        json.putAll(upmsCategoryDictService.getParentInfoById(contentArticle.getCategoryId()));
        return BaseResult.ok(json);
    }

    @Override
    public BaseResult changeStatus(List<String> ids, ContentStatusEnum contentStatusEnum) {
        ContentArticleExample contentArticleExample = new ContentArticleExample();
        contentArticleExample.createCriteria().andIdIn(ids);
        ContentArticle contentArticle = new ContentArticle();
        contentArticle.setStatus(contentStatusEnum.getStatus());
        if (ContentStatusEnum.CONTENT_STATUS_PUBLISHED.getStatus().equals(contentStatusEnum.getStatus())) {
            contentArticle.setPublishDate(System.currentTimeMillis());
        }
        contentArticleMapper.updateByExampleSelective(contentArticle, contentArticleExample);
        return BaseResult.ok();
    }

    @Override
    public BaseResult moveRecycleBin(List<String> ids) {
        ContentArticleExample contentArticleExample = new ContentArticleExample();
        contentArticleExample.createCriteria().andIdIn(ids);
        ContentArticle contentArticle = new ContentArticle();
        contentArticle.setIsDeleted(Byte.valueOf("1"));
        contentArticleMapper.updateByExampleSelective(contentArticle, contentArticleExample);
        return BaseResult.ok();
    }

    @Override
    public BaseResult recovery(List<String> ids) {
        ContentArticleExample contentArticleExample = new ContentArticleExample();
        contentArticleExample.createCriteria().andIdIn(ids);
        ContentArticle contentArticle = new ContentArticle();
        contentArticle.setIsDeleted(Byte.valueOf("0"));
        contentArticleMapper.updateByExampleSelective(contentArticle, contentArticleExample);
        return BaseResult.ok();
    }

    @Override
    public BaseResult setAllowComment(String id, Boolean allowComment) {
        ContentArticle contentArticle = selectByPrimaryKey(id);
        if (ObjectUtil.isEmpty(contentArticle)) {
            return BaseResult.error("无效的内容");
        }
        contentArticle.setIsAllowComment(Boolean.TRUE.equals(allowComment) ? Byte.valueOf("1") : Byte.valueOf("0"));
        contentArticleMapper.updateByPrimaryKeySelective(contentArticle);
        return BaseResult.ok();
    }

    @Override
    public BaseResult view(HttpServletRequest request, String id, CacheUserVO cacheUserVO) {
        BaseResult baseResult = selectDetailsByPrimaryKey(id);
        /**
         * 后期此地方要加浏览数+1
         */
        return baseResult;
    }

    @Override
    public BaseResult analysisByTime(Long dateTime) {
        return BaseResult.ok(contentArticleMapper.analysisByTime(DateUtils.dateTime(dateTime, DateUtils.YYYY_MM)));
    }

    @Override
    public BaseResult findPreAndNext(String id, String categoryId, Boolean isAll) {
        String categoryTree = null;
        if ("all".equals(categoryId)) {
            categoryId = null;
        }
        if (!StringUtil.isNullOrEmpty(categoryId)) {
            categoryTree = upmsCategoryDictService.cacheGetTreeNumberById(categoryId);
        }
        Map<String, ContentArticle> map = new HashMap<>(7);
        map.put("next", contentArticleMapper.findNext(id, categoryTree, isAll));
        map.put("pre", contentArticleMapper.findPrev(id, categoryTree, isAll));

        return BaseResult.ok(map);
    }

    @Override
    public BaseResult syncWxPub(ContentSyncWxPubDto contentSyncWxPubDto) {
        ContentArticle contentArticle = selectByPrimaryKey(contentSyncWxPubDto.getId());
        if (StringUtil.isNullOrEmpty(contentArticle.getId())) {
            return BaseResult.error("无效得文章资源");
        }
        if (Byte.valueOf("1").equals(contentArticle.getSyncMaterialLibrary())) {
            return BaseResult.error("文章已同步至素材库，无需操作！");
        }
        if (!Byte.valueOf("2").equals(contentArticle.getStatus())) {
            return BaseResult.error("当前文章还未发布，禁止同步！");
        }
        ThirdWechatArticle thirdWechatArticle = new ThirdWechatArticle();
        thirdWechatArticle.setId(contentArticle.getId());
        thirdWechatArticle.setGmtCreated(contentArticle.getGmtCreated());
        thirdWechatArticle.setGmtModified(contentArticle.getGmtModified());
        thirdWechatArticle.setIsDeleted(Byte.valueOf("0"));
        thirdWechatArticle.setCreatedBy(contentArticle.getCreatedBy());
        thirdWechatArticle.setModifyBy(contentArticle.getModifyBy());
        thirdWechatArticle.setModifyBy(contentArticle.getModifyBy());
        thirdWechatArticle.setCreatedUserId(contentArticle.getCreatedUserId());
        thirdWechatArticle.setCreatedOrgId(contentArticle.getCreatedOrgId());
        thirdWechatArticle.setTitle(contentArticle.getTitle());
        thirdWechatArticle.setSummary(contentArticle.getSummary());
        thirdWechatArticle.setIsTop(contentArticle.getIsTop());
        thirdWechatArticle.setStatus(Byte.valueOf("2"));
        thirdWechatArticle.setPublishDate(contentArticle.getPublishDate());
        thirdWechatArticle.setIsOriginal(contentArticle.getIsOriginal());
        thirdWechatArticle.setSource(contentArticle.getSource());
        thirdWechatArticle.setSourceUrl(contentArticle.getSourceUrl());
        thirdWechatArticle.setAuthor(contentArticle.getAuthor());
        thirdWechatArticle.setPhoto(contentArticle.getImage1());
        thirdWechatArticle.setResourceType(Byte.valueOf("4"));
        thirdWechatArticle.setAttachment(contentArticle.getFile());
        thirdWechatArticle.setLeavingMessage(Byte.valueOf("1"));
        thirdWechatArticle.setContentBody(contentArticle.getContent());
        thirdWechatArticle.setAppId(contentSyncWxPubDto.getAppId());
        thirdWechatArticle.setCategoryId(contentSyncWxPubDto.getCategory());

        thirdWechatArticleMapper.insertSelective(thirdWechatArticle);
        contentArticle.setSyncMaterialLibrary(Byte.valueOf("1"));
        contentArticleMapper.updateByPrimaryKeySelective(contentArticle);
        return BaseResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult revokeWxPub(String id) {
        ContentArticle contentArticle = selectByPrimaryKey(id);
        if (StringUtil.isNullOrEmpty(contentArticle.getId())) {
            return BaseResult.error("无效得文章资源");
        }
        if (Byte.valueOf("0").equals(contentArticle.getSyncMaterialLibrary())) {
            return BaseResult.error("文章还未同步至素材库，无需操作！");
        }
        thirdWechatArticleMapper.deleteByPrimaryKey(id);
        contentArticle.setSyncMaterialLibrary(Byte.valueOf("0"));
        contentArticleMapper.updateByPrimaryKeySelective(contentArticle);
        return BaseResult.ok();
    }
}
